package com.swak.frame.ratelimit;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.alibaba.fastjson.JSON;
import com.swak.frame.dto.request.SwakRequest;
import com.swak.frame.dto.response.RpcResponse;
import com.swak.frame.exception.SwakAssert;

/**
 * 限流和兜底测试
 * 
 * @ClassName: RateLimitDemoServiceTest.java
 * @author: colley.ma
 * @date: 2022/01/25
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.NONE )
@ComponentScan("com.swak.frame")
public class RateLimitDemoServiceTest {

	@Resource
	private RateLimitDemoService rateLimitDemoService;

	
	@Test
	public void testRateLimitFallBack() {
		SwakRequest request = new SwakRequest();
		request.setPin("colley.ma");
		RpcResponse<String> result = rateLimitDemoService.rateLimitDemoFallBack(request);
		System.out.println(JSON.toJSONString(result));
		SwakAssert.isTrue(result.isSuccess());
	}
	
	@Test
	public void testRateLimit() {
		SwakRequest request = new SwakRequest();
		request.setPin("colley.ma");
		RpcResponse<String> result = rateLimitDemoService.rateLimitDemo(request);
		System.out.println(JSON.toJSONString(result));
		SwakAssert.isTrue(result.isSuccess());
	}
	
	@Test
	public void testRateLimitFallBackByThread() {
		for (int i = 0; i < 10; i++) {
			new Thread(() -> {
				SwakRequest request = new SwakRequest();
				request.setPin("colley.ma");
				RpcResponse<String> result = rateLimitDemoService.rateLimitDemoFallBack(request);
				System.out.println(JSON.toJSONString(result));
			}).start();
		}
	}

	@Test
	public void testRateLimitByThread() {
		for (int i = 0; i < 10; i++) {
			new Thread(() -> {
				SwakRequest request = new SwakRequest();
				request.setPin("colley.ma");
				RpcResponse<String> result = rateLimitDemoService.rateLimitDemo(request);
				System.out.println(JSON.toJSONString(result));
			}).start();
		}
	}
}
